<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/%E5%8D%9A%E5%AE%A2.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/%E5%8D%9A%E5%AE%A2.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/%E5%8D%9A%E5%AE%A2.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Spring,SpringBoot," />





  <link rel="alternate" href="/atom.xml" title="Createsequence's Blog" type="application/atom+xml" />






<meta name="description" content="概述 从 spring3 开始，spring 开始支持缓存组件，并提供了一系列非常方便的注解。 其中，Cache 接口定义了基本的增删改查方法，Spring 提供了一些默认的实现，比如 RedisCache 等。 CacheManager 接口则用于接入并获取 Redis 这样的缓存组件。 在 springboot 中，当我们启用缓存以后，需要如果要将接入 Redis 作为缓存，就需要配置">
<meta property="og:type" content="article">
<meta property="og:title" content="使用SpringCache做简单缓存">
<meta property="og:url" content="http://blog.xiajibagao.top/2019/07/23/spring/%E4%BD%BF%E7%94%A8SpringCache%E5%81%9A%E7%AE%80%E5%8D%95%E7%BC%93%E5%AD%98/index.html">
<meta property="og:site_name" content="Createsequence&#39;s Blog">
<meta property="og:description" content="概述 从 spring3 开始，spring 开始支持缓存组件，并提供了一系列非常方便的注解。 其中，Cache 接口定义了基本的增删改查方法，Spring 提供了一些默认的实现，比如 RedisCache 等。 CacheManager 接口则用于接入并获取 Redis 这样的缓存组件。 在 springboot 中，当我们启用缓存以后，需要如果要将接入 Redis 作为缓存，就需要配置">
<meta property="og:locale">
<meta property="article:published_time" content="2019-07-22T16:00:00.000Z">
<meta property="article:modified_time" content="2020-11-24T08:59:08.511Z">
<meta property="article:author" content="Createsequence">
<meta property="article:tag" content="Spring">
<meta property="article:tag" content="SpringBoot">
<meta name="twitter:card" content="summary">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":true,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://blog.xiajibagao.top/2019/07/23/spring/使用SpringCache做简单缓存/"/>





  <title>使用SpringCache做简单缓存 | Createsequence's Blog</title>
  








<meta name="generator" content="Hexo 5.2.0"></head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Createsequence's Blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">一个努力前进的程序猿</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://blog.xiajibagao.top/2019/07/23/spring/%E4%BD%BF%E7%94%A8SpringCache%E5%81%9A%E7%AE%80%E5%8D%95%E7%BC%93%E5%AD%98/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/Createsequence.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Createsequence's Blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">使用SpringCache做简单缓存</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2019-07-23T00:00:00+08:00">
                2019-07-23
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/SpringBoot/" itemprop="url" rel="index">
                    <span itemprop="name">SpringBoot</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  1.6k
                </span>
              

              

              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h2 id="概述">概述</h2>
<p>从 spring3 开始，spring 开始支持缓存组件，并提供了一系列非常方便的注解。</p>
<p>其中，Cache 接口定义了基本的增删改查方法，Spring 提供了一些默认的实现，比如 RedisCache 等。 CacheManager 接口则用于接入并获取 Redis 这样的缓存组件。</p>
<p>在 springboot 中，当我们启用缓存以后，需要如果要将接入 Redis 作为缓存，就需要配置 RedisCacheManager，其他缓存组件亦同。当没有自定义的缓存的时候，就会使用默认的 ConcurrentMapCacheManager，即将缓存存入本地的一个 Map 集合中。</p>
<h2 id="一-配置">一、配置</h2>
<h3 id="1添加依赖">1.添加依赖</h3>
<p>在创建项目的时候直接在 springboot 启动器中配置，或在项目中添加 Maven 依赖：</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.springframework.boot<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>spring-boot-starter-cache<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br></pre></td></tr></table></figure>
<h3 id="2-启用注解">2. 启用注解</h3>
<p>在启动类或者配置类里添加 <span class="citation" data-cites="EnableCaching">@EnableCaching</span> 注解开启缓存</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@EnableCaching</span><span class="comment">//开启缓存</span></span><br><span class="line"><span class="meta">@SpringBootApplication</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">SpringbootCacheApplication</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        SpringApplication.run(SpringbootCacheApplication.class, args);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><strong>注意：由于 Spring 的 AOP 基于 CGLib 代理，所以如果在本类调用成员方法，因为不走代理所以缓存是不会生效的。</strong></p>
<h2 id="二-注解与-spel-表达式">二、注解与 SpEL 表达式</h2>
<h3 id="1缓存注解">1.缓存注解</h3>
<table>
<thead>
<tr class="header">
<th>注解</th>
<th>解释</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td><span class="citation" data-cites="EnableCaching">@EnableCaching</span></td>
<td>开启基于注解的缓存</td>
</tr>
<tr class="even">
<td><span class="citation" data-cites="CacheConfig">@CacheConfig</span></td>
<td>统一配置本类的缓存注解的属性</td>
</tr>
<tr class="odd">
<td><span class="citation" data-cites="Cacheable">@Cacheable</span></td>
<td>第一次调用方法后都将返回值存入缓存，下次则请求直接调用缓存</td>
</tr>
<tr class="even">
<td><span class="citation" data-cites="CachePut">@CachePut</span></td>
<td>每次调用方法后都将返回值存入缓存，用于缓存更新</td>
</tr>
<tr class="odd">
<td><span class="citation" data-cites="CacheEvict">@CacheEvict</span></td>
<td>清除缓存</td>
</tr>
<tr class="even">
<td><span class="citation" data-cites="Caching">@Caching</span></td>
<td>组合注解，即给一个方法同时设置多个缓存方案</td>
</tr>
</tbody>
</table>
<h3 id="2-spel-表达式">2. SpEL 表达式</h3>
<p>spring 表达式支持我们通过指定的明确获取参数或者方法的属性：</p>
<table>
<colgroup>
<col style="width: 11%">
<col style="width: 8%">
<col style="width: 53%">
<col style="width: 25%">
</colgroup>
<thead>
<tr class="header">
<th>名称</th>
<th>位置</th>
<th>描述</th>
<th>示例</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>methodName</td>
<td>root对象</td>
<td>当前被调用的方法名</td>
<td>#root.methodname</td>
</tr>
<tr class="even">
<td>method</td>
<td>root对象</td>
<td>当前被调用的方法</td>
<td>#root.method.name</td>
</tr>
<tr class="odd">
<td>target</td>
<td>root对象</td>
<td>当前被调用的目标对象实例</td>
<td>#root.target</td>
</tr>
<tr class="even">
<td>targetClass</td>
<td>root对象</td>
<td>当前被调用的目标对象的类</td>
<td>#root.targetClass</td>
</tr>
<tr class="odd">
<td>args</td>
<td>root对象</td>
<td>当前被调用的方法的参数列表</td>
<td>#root.args[0]<br>#root.参数名</td>
</tr>
<tr class="even">
<td>caches</td>
<td>root对象</td>
<td>当前方法调用使用的缓存列表</td>
<td>#root.caches[0].name</td>
</tr>
<tr class="odd">
<td>Argument Name</td>
<td>执行上下文</td>
<td>当前被调用的方法的参数，如findArtisan(Artisan artisan),可以通过#artsian.id获得参数</td>
<td>#artsian.id</td>
</tr>
<tr class="even">
<td>result</td>
<td>执行上下文</td>
<td>法执行后的返回值（仅当方法执行后的判断有效，如 unless cacheEvict的beforeInvocation=false）</td>
<td>#result</td>
</tr>
</tbody>
</table>
<p>因为默认对象即为 #root，所以写的时候可以直接省略 #root</p>
<p>此外，表达式同样支持运算符：</p>
<table>
<thead>
<tr class="header">
<th>类型</th>
<th>运算符</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>关系</td>
<td>&lt;，&gt;，&lt;=，&gt;=，==，!=，lt，gt，le，ge，eq，ne</td>
</tr>
<tr class="even">
<td>算术</td>
<td>+，- ，* ，/，%，^</td>
</tr>
<tr class="odd">
<td>逻辑</td>
<td>&amp;&amp;，||，!，and，or，not，between，instanceof</td>
</tr>
<tr class="even">
<td>条件</td>
<td>?: (ternary)，?: (elvis)</td>
</tr>
</tbody>
</table>
<h2 id="三-使用">三、使用</h2>
<h3 id="1添加缓存">1.添加缓存</h3>
<p><span class="citation" data-cites="Cacheable">@Cacheable</span> 注解用于标记方法。第一次执行的时候，会将方法结果存入缓存，再次调用该方法，<strong>在执行前</strong>，如果 key 相同则直接返回缓存中的数据，不会再次执行方法。</p>
<p>他的主要属性有以下五种：</p>
<ul>
<li>value/cacheName：指定缓存命名空间，只有保证命名空间相同，key 才能找到对应的缓存。</li>
<li>key：指定缓存数据的键值对的key，默认为方法参数中的值；</li>
<li>Condition：指定缓存执行的条件；</li>
<li>unliss：指定缓存不执行的条件；</li>
<li>sync：指定缓存是否使用异步模式，默认同步，若异步则不支持 unless。这个主要是用来处理多线程环境下缓存更新导致数据出错的问题的。</li>
</ul>
<p>上述一些复杂的条件依赖于 sqEl 表达式</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment"> * 方法调用给前进行检测，若存在 key 对应的数据则直接从缓存中返回结果，否则在执行后将返回值存入缓存</span></span><br><span class="line"><span class="comment"> * */</span></span><br><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="meta">@Cacheable(cacheNames = &quot;dept&quot;，key = &quot;targetClass&quot;)</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> List&lt;Dept&gt; <span class="title">findAll</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    System.out.println(<span class="string">&quot;全查！&quot;</span>);</span><br><span class="line">    <span class="keyword">return</span> mapper.selectAll();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="2缓存更新">2.缓存更新</h3>
<p><span class="citation" data-cites="CachePut">@CachePut</span> 注解一般用于更新某个命名空间中的某条缓存数据。<strong>当方法调用结束以后</strong>，会根据注解将结果存入缓存，如果 key 已经存在，则会更新缓存。</p>
<p>他的主要属性同 <span class="citation" data-cites="Cacheable">@Cacheable</span> 基本相同，但是由于是先执行才处理数据，所以 key 是可以获得 #root.result 的。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">* 调用方法后，再把返回值放入缓存</span></span><br><span class="line"><span class="comment">* */</span></span><br><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="meta">@CachePut(cacheNames = &quot;dept&quot;，key = &quot;#root.targetClass&quot;)</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> List&lt;Dept&gt; <span class="title">add</span><span class="params">(Dept dept)</span> </span>&#123;</span><br><span class="line">    System.out.println(<span class="string">&quot;增加！&quot;</span>);</span><br><span class="line">    mapper.insert(dept);</span><br><span class="line">    <span class="keyword">return</span> mapper.selectAll();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="3清空缓存">3.清空缓存</h3>
<p><span class="citation" data-cites="CacheEvict">@CacheEvict</span> 用于清空某个命名空间内某条、或全部缓存数据。</p>
<p>他的主要属性就两个：</p>
<ul>
<li><p>allEntries：是否清空全部缓存数据。默认 true，会忽略 key，否则只清除 key 对应的缓存；</p></li>
<li><p>beforeInvocation：是否要在方法执行前就清空缓存。默认为 false，即执行结束后才清空缓存。</p>
<p>注意：当发生异常时，是不会清空缓存的。</p></li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment"> * 清除缓存中的数据</span></span><br><span class="line"><span class="comment"> * */</span></span><br><span class="line"><span class="meta">@CacheEvict(cacheNames = &quot;dept&quot;, key = &quot;#root.targetClass&quot;, beforeInvocation = false)</span></span><br><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">delete</span><span class="params">(Integer deptno)</span> </span>&#123;</span><br><span class="line">    System.out.println(<span class="string">&quot;删除！&quot;</span>);</span><br><span class="line">    mapper.deleteByPrimaryKey(deptno);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="4多条件组合">4.多条件组合</h3>
<p><span class="citation" data-cites="Caching">@Caching</span> 是一个组合注解，可以在里面添加复数的以上三种注解。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment"> * 组合注解，三种注解以每种可有多个，以数组形式存储</span></span><br><span class="line"><span class="comment"> * */</span></span><br><span class="line"><span class="meta">@Caching(</span></span><br><span class="line"><span class="meta">    cacheable = &#123;</span></span><br><span class="line"><span class="meta">        //添加一个缓存</span></span><br><span class="line"><span class="meta">        @Cacheable(value = &quot;dept&quot;,key = &quot;#deptno&quot;)</span></span><br><span class="line"><span class="meta">    &#125;,</span></span><br><span class="line"><span class="meta">    put = &#123;</span></span><br><span class="line"><span class="meta">        //更新一个缓存</span></span><br><span class="line"><span class="meta">        @CachePut(value = &quot;emp&quot;，key = &quot;#root.targetClass&quot;)</span></span><br><span class="line"><span class="meta">    &#125;,</span></span><br><span class="line"><span class="meta">    evict = &#123;</span></span><br><span class="line"><span class="meta">        //清除一个缓存</span></span><br><span class="line"><span class="meta">        @CacheEvict(value = &quot;person&quot;，key = &quot;#deptno&quot;)</span></span><br><span class="line"><span class="meta">    &#125;</span></span><br><span class="line"><span class="meta">)</span></span><br><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> Dept <span class="title">findById</span><span class="params">(Integer deptno)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="5统一命名空间">5.统一命名空间</h3>
<p><span class="citation" data-cites="CacheConfig">@CacheConfig</span> 注解可以在类上统一命名空间，这样类中如果没有指定 cacheName 或者 value，那么默认会使用 <span class="citation" data-cites="CacheConfig">@CacheConfig</span> 指定的命名空间。当然，如果在方法上自己指定了另外的命名空间，则以方法上的注解为准。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//使用@CacheConfig统一cacheName，如果在方法上仍写了value，则该方法值仍以value为准</span></span><br><span class="line"><span class="meta">@CacheConfig(cacheNames = &quot;dept&quot;)</span></span><br><span class="line"><span class="meta">@Service</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">DeptServiceImp</span> <span class="keyword">implements</span> <span class="title">DeptService</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Resource</span></span><br><span class="line">    <span class="keyword">private</span> DeptMapper mapper;</span><br><span class="line">    </span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="meta">@Cacheable(key = &quot;targetClass&quot;)</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> List&lt;Dept&gt; <span class="title">findAll</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;全查！&quot;</span>);</span><br><span class="line">        <span class="keyword">return</span> mapper.selectAll();</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="meta">@CachePut(key = &quot;targetClass&quot;)</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> List&lt;Dept&gt; <span class="title">add</span><span class="params">(Dept dept)</span> </span>&#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;增加！&quot;</span>);</span><br><span class="line">        mapper.insert(dept);</span><br><span class="line">        <span class="keyword">return</span> mapper.selectAll();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@CachePut(key = &quot;targetClass&quot;)</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> List&lt;Dept&gt; <span class="title">delete</span><span class="params">(Integer deptno)</span> </span>&#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;删除！&quot;</span>);</span><br><span class="line">        mapper.deleteByPrimaryKey(deptno);</span><br><span class="line">        <span class="keyword">return</span> mapper.selectAll();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Spring/" rel="tag"># Spring</a>
          
            <a href="/tags/SpringBoot/" rel="tag"># SpringBoot</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2019/07/24/linux/linux%E4%B8%8B%E5%AE%89%E8%A3%85tomcat/" rel="prev" title="linux下安装tomcat">
                linux下安装tomcat <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/images/Createsequence.jpg"
                alt="" />
            
              <p class="site-author-name" itemprop="name"></p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/%7C%7Carchive">
              
                  <span class="site-state-item-count">89</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">15</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">21</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%A6%82%E8%BF%B0"><span class="nav-text">概述</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E4%B8%80-%E9%85%8D%E7%BD%AE"><span class="nav-text">一、配置</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1%E6%B7%BB%E5%8A%A0%E4%BE%9D%E8%B5%96"><span class="nav-text">1.添加依赖</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-%E5%90%AF%E7%94%A8%E6%B3%A8%E8%A7%A3"><span class="nav-text">2. 启用注解</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E4%BA%8C-%E6%B3%A8%E8%A7%A3%E4%B8%8E-spel-%E8%A1%A8%E8%BE%BE%E5%BC%8F"><span class="nav-text">二、注解与 SpEL 表达式</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1%E7%BC%93%E5%AD%98%E6%B3%A8%E8%A7%A3"><span class="nav-text">1.缓存注解</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-spel-%E8%A1%A8%E8%BE%BE%E5%BC%8F"><span class="nav-text">2. SpEL 表达式</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E4%B8%89-%E4%BD%BF%E7%94%A8"><span class="nav-text">三、使用</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1%E6%B7%BB%E5%8A%A0%E7%BC%93%E5%AD%98"><span class="nav-text">1.添加缓存</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2%E7%BC%93%E5%AD%98%E6%9B%B4%E6%96%B0"><span class="nav-text">2.缓存更新</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3%E6%B8%85%E7%A9%BA%E7%BC%93%E5%AD%98"><span class="nav-text">3.清空缓存</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#4%E5%A4%9A%E6%9D%A1%E4%BB%B6%E7%BB%84%E5%90%88"><span class="nav-text">4.多条件组合</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#5%E7%BB%9F%E4%B8%80%E5%91%BD%E5%90%8D%E7%A9%BA%E9%97%B4"><span class="nav-text">5.统一命名空间</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2022</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Createsequence</span>

  
</div>






  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Gemini</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
          <span id="scrollpercent"><span>0</span>%</span>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  

  

  


  <!-- 引入目录截取js -->
  <script type="text/javascript" src="/js/src/custom/custom.js"></script>
</body>
</html>
